const router = require('koa-router')()
let Admin = require('../../models/Admin')
let tools = require('../../model/tools')


router.get('/', async (ctx) => {
  await Admin.find({}).then(result => {
    ctx.render('admin/manage/list', {
      list: result
    })
  })
})

router.get('/add', async (ctx) => {
  await ctx.render('admin/manage/add')
})
//增加管理员
router.post('/doAdd', async (ctx) => {
  let {username, password, rpassword} = ctx.request.body
  if (!/^\w{4,20}/.test(username)) {
    ctx.render('admin/error', {
      message: '用户名不合法',
      redirect: `${ctx.state.__HOST__}/admin/manage/add`
    })
  } else if (password !== rpassword || password.length < 6) {
    ctx.render('admin/error', {
      message: '密码和确认密码不一致,或者长度小于6位',
      redirect: `${ctx.state.__HOST__}/admin/manage/add`
    })
  } else {
    await Admin.findOne({
      username
    }).then(async usernameData => {
      if (usernameData) {
        ctx.render('admin/error', {
          message: '用户名已存在',
          redirect: `${ctx.state.__HOST__}/admin/manage/add`
        })
      } else {
        let user = new Admin({
          username,
          password: tools.md5(password),
          rpassword: tools.md5(rpassword),
          status: 1,
          last_time: ''
        })

        await user.save().then(addResult => {
          console.log(addResult)
          console.log(ctx.state.__HOST__ + '/admin/manage')
          ctx.redirect(ctx.state.__HOST__ + '/admin/manage')
        })
      }
    })
  }
})

router.get('/edit', async (ctx) => {
  let {id} = ctx.query
  await Admin.findById(id).then(async result => {
    if (result) {
      await ctx.render('admin/manage/edit', {
        list: result
      })
    }
  })
})

router.post('/doEdit', async (ctx) => {
  let {username, password, rpassword, id} = ctx.request.body
  if (password !== '') {
    if (password !== rpassword || password.length < 6) {
      ctx.render('admin/error', {
        message: '密码和确认密码不一致,或者长度小于6位',
        redirect: `${ctx.state.__HOST__}/admin/manage/edit?id=${id}`
      })
    } else {
      await Admin.findByIdAndUpdate(id, {
        password: tools.md5(password),
        rpassword: tools.md5(rpassword)
      }).then(async result => {
        if (result) {
          await ctx.redirect(ctx.state.__HOST__ + '/admin/manage')
        }
      })
    }
  }
  await ctx.redirect(ctx.state.__HOST__ + '/admin/manage')
})


module.exports = router.routes()